﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Entity.Infrastructure;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace Expressing_Label
{
    public partial class LableByOtherFrm : Form
    {
        private SubExpressingInfo[] c_TmpExpressingArray = null;
        private SubExpressingInfo[] c_tbExpressingArray = new SubExpressingInfo[105];
        private Queue<SubExpressingInfo> queueSubExpInfo = new Queue<SubExpressingInfo>();
        private int c_iValuableExpSum = 0;
        private int c_iCurrentIndex = 0;
        private int c_iNumToQuery = 0;
        private string c_strTmpExpressing = "";
        private Thread c_threadSaveToSQL = null;
        private bool c_isFrmMoving = false;
        private Point c_ptCurrentPosition = new Point();

        public LableByOtherFrm()
        {
            InitializeComponent();
            InitializeExpressing();
            InitializeData();
        }

        private void InitializeExpressing()
        {
            for (int i = 0; i < PublicResources.g_ExpressingSourceItem.Count; i += 5)
            {
                int j = i / 5;
                foreach (Control c in ExpressionGroup.Controls)
                {
                    if (c is GroupBox && c.TabIndex == j + 7)                                               //Set GroupName
                    {
                        (c as GroupBox).Text = PublicResources.g_ExpressingSourceItem[i];
                        foreach (Control r in c.Controls)
                        {
                            if (r is RadioButton)
                            {
                                (r as RadioButton).Enabled = false;
                                (r as RadioButton).Visible = false;
                            }
                        }
                        int t = 0;
                        for (int k = 1; k < 5; k++)
                        {
                            string s = PublicResources.g_ExpressingSourceItem[j * 5 + k];
                            if (!s.EndsWith("0"))
                            {
                                foreach (Control r in c.Controls)
                                    if (r is RadioButton && (r as RadioButton).TabIndex == t)
                                    {
                                        t++;
                                        RadioButton tr = (RadioButton)r;
                                        tr.Visible = true;
                                        tr.Enabled = true;
                                        tr.Text = s;
                                        tr.CheckedChanged += new System.EventHandler(this.Radio_CheckedChanged);
                                        break;
                                    }
                            }
                        }
                    }
                }
            }
        }

        //多个groupbox中多个radiobutton单选处理
        private void Radio_CheckedChanged(object sender, EventArgs e)
        {
            if (sender is RadioButton)
            {
                if (((RadioButton)sender).Checked)
                {
                    GroupBox gb = ((RadioButton)sender).Parent as GroupBox;
                    foreach (Control c in ExpressionGroup.Controls)
                    {
                        if (c is GroupBox && !c.Equals(gb))
                        {
                            foreach (Control cc in c.Controls)
                            {
                                if (cc is RadioButton)
                                    (cc as RadioButton).Checked = false;
                            }
                        }
                    }
                }
            }
        }

        private void InitializeData()
        {
            c_iNumToQuery = PublicResources.g_iUserNum * PublicResources.g_iNumToLabel;
            using (var db = new db_FACEEntities())
            {
                var result = (from info in db.tb_ExpressingInfo
                              where info.OtherTimes <= 10 && info.MaxTimes < 5
                              orderby info.OtherTimes ascending
                              select new SubExpressingInfo()
                              {
                                  ID = info.ID,
                                  OtherTimes = info.OtherTimes,
                                  ImageLocation = info.ImageLocation,
                                  TmpExpressing = "",
                                  OtherExpressing = info.Expressing_OtherDetail,
                                  MaxTimes = info.MaxTimes,
                                  MaxExpressing = info.MaxEpressing
                              }
                              ).Take(c_iNumToQuery);
                c_TmpExpressingArray = result.ToArray();
                c_iValuableExpSum = c_TmpExpressingArray.Count() / PublicResources.g_iUserNum;
                int t = PublicResources.g_iUserID;
                t %= PublicResources.g_iUserNum;
                for (int i = 0; i < c_iValuableExpSum; i++)
                {
                    c_tbExpressingArray[i] = c_TmpExpressingArray[t * c_iValuableExpSum + i];
                }
            }
        }

        private void LableByOtherFrm_Load(object sender, EventArgs e)
        {
            if (c_iValuableExpSum > 0)
            {
                lblSumOfExp.Text = "您有" + c_iValuableExpSum.ToString() + "张等待标注";
                lblLeftExp.Text = "还剩：" + c_iValuableExpSum.ToString() + "张";
                RefreshInfo(0);
                c_iCurrentIndex = 0;
            }
        }

        private void RefreshInfo(int index)
        {
            picbxExpressing.ImageLocation = c_tbExpressingArray[index].ImageLocation + "_min.png";
            lblTimes.Text = "第" + (c_tbExpressingArray[index].OtherTimes + 1).ToString() + "次标注";
        }

        private void picbxExpressing_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            CheckAndSave_Mtd();
        }

        private void CheckAndSave_Mtd()
        {
            bool m_isChecked = false;
            foreach (Control c in ExpressionGroup.Controls)
            {
                if (c is GroupBox)
                {
                    foreach (Control cc in c.Controls)
                    {
                        if (cc is RadioButton && (cc as RadioButton).Checked == true)
                        {
                            m_isChecked = true;
                            c_strTmpExpressing = (cc as RadioButton).Text;
                            (cc as RadioButton).Checked = false;
                            break;
                        }
                    }
                }
                if (m_isChecked)
                    break;
            }

            if (m_isChecked && c_iCurrentIndex < c_iValuableExpSum)
            {
                
                c_tbExpressingArray[c_iCurrentIndex].TmpExpressing = c_strTmpExpressing;
                c_tbExpressingArray[c_iCurrentIndex].OtherTimes++;
                queueSubExpInfo.Enqueue(c_tbExpressingArray[c_iCurrentIndex]);
                if (c_iCurrentIndex % 10 == 9 || c_iCurrentIndex == c_iValuableExpSum - 1)
                {
                    c_threadSaveToSQL = new Thread(SaveChangeToSQL);
                    c_threadSaveToSQL.IsBackground = true;
                    c_threadSaveToSQL.Start();
                }
                c_iCurrentIndex++;
                lblLeftExp.Text = "还剩：" + (c_iValuableExpSum - c_iCurrentIndex).ToString() + "张";
                if (c_iCurrentIndex != c_iValuableExpSum)
                {
                    RefreshInfo(c_iCurrentIndex);
                }
            }
            else if (c_iCurrentIndex == c_iValuableExpSum)
                MessageBox.Show("Already Finished!");
            else if (!m_isChecked)
                MessageBox.Show("Missing Chosing Expressing!");
            
        }

        private void SaveChangeToSQL()
        {
            using (var db = new db_FACEEntities())
            {
                while(queueSubExpInfo.Count > 0)
                {
                    SubExpressingInfo tmpsub = queueSubExpInfo.Dequeue();
                    tb_ExpressingInfo tmptb = new tb_ExpressingInfo();
                    tmptb.ID = tmpsub.ID;
                    tmptb.OtherTimes = tmpsub.OtherTimes;
                    db.tb_ExpressingInfo.Attach(tmptb);
                    var setEntry = ((IObjectContextAdapter)db).ObjectContext.ObjectStateManager.GetObjectStateEntry(tmptb);

                    string[] tmpExpressing = tmpsub.OtherExpressing.Split(new Char[] { ',' });
                    if (tmpsub.MaxTimes == 0 || tmpsub.TmpExpressing == tmpsub.MaxExpressing)
                        tmpsub.MaxTimes++;
                    else
                    {
                        int t = 0;
                        for (int i = 0; i < tmpsub.OtherTimes - 1; i++)
                        {
                            if (tmpExpressing[i] == tmpsub.TmpExpressing)
                                t++;
                        }
                        if (t == tmpsub.MaxTimes)
                        {
                            tmpsub.MaxTimes++;
                        }
                    }
                    tmptb.MaxTimes = tmpsub.MaxTimes;
                    tmptb.MaxEpressing = tmpsub.MaxExpressing;
                    if (tmptb.MaxTimes == 5)
                    {
                        tmptb.Expressing_Oth = tmptb.MaxEpressing;
                        setEntry.SetModifiedProperty("Expressing_Oth");
                    }
                    tmpExpressing[tmpsub.OtherTimes - 1] = tmpsub.TmpExpressing;
                    string ts = "";
                    for (int i = 0; i < tmpExpressing.Length; i++)
                    {
                        ts += tmpExpressing[i];
                        if (i < tmpExpressing.Length - 1)
                            ts += ",";
                    }
                    tmptb.Expressing_OtherDetail = ts;

                    
                    setEntry.SetModifiedProperty("OtherTimes");
                    setEntry.SetModifiedProperty("Expressing_OthDetail");
                    setEntry.SetModifiedProperty("MaxTimes");
                    setEntry.SetModifiedProperty("MaxExpressing");
                        
                }
                db.Configuration.ValidateOnSaveEnabled = false;
                db.SaveChanges();
                db.Configuration.ValidateOnSaveEnabled = true;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            SaveChangeToSQL();
        }

        private void btnBack_Click(object sender, EventArgs e)
        {
            PromptShow_Thd();        
            if (queueSubExpInfo.Count > 0 && (c_threadSaveToSQL == null || !c_threadSaveToSQL.IsAlive))
            {
                c_threadSaveToSQL = new Thread(SaveChangeToSQL);
                c_threadSaveToSQL.IsBackground = true;
                c_threadSaveToSQL.Start();
                Thread.Sleep(900);
            }
            timClosing.Start();          
        }

        private void PromptShow_Thd()
        {
            PromptFrm pf = new PromptFrm("保存数据中，请稍候");
            pf.Show();
        }

        private void bntNext_Click(object sender, EventArgs e)
        {
            CheckAndSave_Mtd();
        }

        private void LableByOtherFrm_MouseDown(object sender, MouseEventArgs e)
        {
            c_isFrmMoving = true;
            c_ptCurrentPosition = MousePosition;
        }

        private void LableByOtherFrm_MouseMove(object sender, MouseEventArgs e)
        {
            if (c_isFrmMoving)
            {
                this.Left += MousePosition.X - c_ptCurrentPosition.X;
                this.Top += MousePosition.Y - c_ptCurrentPosition.Y;
                c_ptCurrentPosition = MousePosition;
            }
        }

        private void LableByOtherFrm_MouseUp(object sender, MouseEventArgs e)
        {
            c_isFrmMoving = false;
        }

        private void LableByOtherFrm_MouseLeave(object sender, EventArgs e)
        {
            c_isFrmMoving = false;
        }

        private void timClosing_Tick(object sender, EventArgs e)
        {
            if (queueSubExpInfo.Count == 0)
            {
                if (c_threadSaveToSQL != null)
                    c_threadSaveToSQL.Abort();
                this.Owner.Show();
                this.Close();
            }
        }
        

        //private void LableByOtherFrm_MouseUp(object sender, MouseEventArgs e)
        //{
        //    c_isFrmMoving = false;
        //}

        //private void LableByOtherFrm_MouseLeave(object sender, EventArgs e)
        //{
        //    c_isFrmMoving = false;
        //}

        //private void timClosing_Tick(object sender, EventArgs e)
        //{
        //    if (queueSubExpInfo.Count == 0)
        //    {
        //        if (c_threadSaveToSQL != null)
        //            c_threadSaveToSQL.Abort();
        //        this.Owner.Show();
        //        this.Close();
        //    }
        //}

    }
}
